package com.smile.frame.config.warn.contsants.dingding;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.URLUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.smile.frame.config.warn.contsants.constant.DingTalkConstant;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author LGC
 */
public class DingTalkUtil {

    public static boolean sendText(String message, String title) throws Exception {
        Long timestamp = System.currentTimeMillis();
        String sign = getSign(timestamp);
        String url = DingTalkConstant.url + "&timestamp=" + timestamp + "&sign=" + sign;
        //设置发送消息
        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        markdown.setTitle(title == null ? "异常信息" : title);
        markdown.setText(message);
        //实例化请求对象
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("markdown");
        request.setMarkdown(markdown);
        //实例化发送对象
        DingTalkClient client = new DefaultDingTalkClient(url);
        OapiRobotSendResponse response = client.execute(request);
        if (response.isSuccess()) {
            return true;
        }
        return false;
    }

    private static String getSign(Long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + DingTalkConstant.secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(DingTalkConstant.secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        String encode = Base64.encode(signData);
        return URLUtil.encode(encode);
    }


}
